package com.example.weiwing.home.dynamic;

import static java.lang.Thread.sleep;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.example.weiwing.Loginmain.LoginEdit;
import com.example.weiwing.R;
import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.entity.Article;
import com.example.weiwing.util.SpUtils;
import com.example.weiwing.util.ViewPagerLayoutManager;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;

import java.util.ArrayList;
import java.util.List;



public class DynamicFragment extends Fragment {
    private View view;
    private RecyclerView rvDynamic;
    private DynamicAdapter mAdapter;
    private ViewPagerLayoutManager mViewPagerLayoutManager;
    private int mCurrentPosition = -1;
    private Context context;
    private List<Dynamic> dynamicList;
    private Handler mHandler;
    private List<Article> articleList = new ArrayList<>();



    private int pageNum = 1;
    private int pageSize = 3;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // TODO: 前端也固定一下只能选择照片格式，使用开源项目

        view = inflater.inflate(R.layout.fragment_dynamic, container, false);

        //  定义 下拉刷新
        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                System.out.println("1111");
                articleList.clear();
                pageNum = 0;
                loadMoreData(1);
            }
        });

        // 上拉加载


        // 初始化 RecyclerView
        rvDynamic = view.findViewById(R.id.recycler_view_dynamic);

        rvDynamic.setLayoutManager(new LinearLayoutManager(getContext()));

        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    mAdapter.notifyDataSetChanged();
                    mSwipeRefreshLayout.setRefreshing(false);
                } else if (msg.what == 2) {

                }
            }
        };

        new DynamicListThread(pageNum, pageSize, 3).start();

        mAdapter = new DynamicAdapter(getActivity(), articleList);
        rvDynamic.setAdapter(mAdapter);

        rvDynamic.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(!recyclerView.canScrollVertically(1)){
                    loadMoreData(2);
                }
            }
        });

        return view;
    }

    public static boolean isVisBottom(RecyclerView recyclerView){
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
                return true;
        }
        return false;
    }

    private void loadMoreData(int i) {
        // 增加 pageNum 的值，并调用新的 DynamicListThread 实例
        pageNum++;
        new DynamicListThread(pageNum, pageSize, i).start();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    public class DynamicListThread extends Thread {
        private int pageNum;
        private int pageSize;
        private int i;

        public DynamicListThread(int pageNum, int pageSize, int i) {
            super();
            this.pageNum = pageNum;
            this.pageSize = pageSize;
            this.i = i;
        }

        @Override
        public void run() {
            // 请求加载更多数据
            HttpRequest.build(getActivity(), WeiWingConfig.getUrl() + "/article/list")
                    .addHeaders("token", SpUtils.getString(getActivity(), "token"))
                    .addParameter("pageNum", pageNum)
                    .addParameter("pageSize", pageSize)
                    .setResponseListener(new ResponseListener() {
                        @Override
                        public void onResponse(String response, Exception error) {
                            // 处理加载结果
                            if (error == null) {
                                JSONObject jsonObject = JSON.parseObject(response);
                                if (jsonObject.getInteger("code") == 200) {
                                    JSONArray rows = jsonObject.getJSONArray("rows");
                                    List<Article> articles = JSON.parseObject(rows.toJSONString(), new TypeReference<List<Article>>() {
                                    });
                                    // 首先发送消息
                                    mHandler.obtainMessage(i).sendToTarget();
                                    // 然后在主线程中更新 UI
                                    articleList.addAll(articles);
                                    mAdapter.notifyDataSetChanged();
                                } else {
                                    Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).doGet();
        }
    }
}